package org.apache.flink.runtime.highavailability.nonha.embedded;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.flink.api.common.ConsumerID;
import org.apache.flink.runtime.highavailability.AbstractThreadsafeJobResultStore;
import org.apache.flink.runtime.highavailability.ConsumeResultEntry;
import org.apache.flink.runtime.highavailability.ConsumeResultStore;
import org.apache.flink.runtime.resourceconsumer.ConsumeResult;

/** A thread-safe in-memory implementation of the {@link ConsumeResultStore}. */
public class EmbeddedJobResultStore extends AbstractThreadsafeJobResultStore {

    private final Map<ConsumerID, ConsumeResultEntry> dirtyJobResults = new HashMap<>();

    private final Map<ConsumerID, ConsumeResultEntry> cleanJobResults = new HashMap<>();

    @Override
    public void createDirtyResultInternal(ConsumeResultEntry jobResultEntry) {
        dirtyJobResults.put(jobResultEntry.getJobId(), jobResultEntry);
    }

    @Override
    public void markResultAsCleanInternal(ConsumerID jobId) throws IOException, NoSuchElementException {
        final ConsumeResultEntry jobResultEntry = dirtyJobResults.remove(jobId);
        if (jobResultEntry != null) {
            cleanJobResults.put(jobId, jobResultEntry);
        } else {
            throw new NoSuchElementException(
                    String.format(
                            "Could not mark job %s as clean as it is not present in the job result store.",
                            jobId));
        }
    }

    @Override
    public boolean hasDirtyJobResultEntryInternal(ConsumerID jobId) throws IOException {
        return dirtyJobResults.containsKey(jobId);
    }

    @Override
    public boolean hasCleanJobResultEntryInternal(ConsumerID jobId) throws IOException {
        return cleanJobResults.containsKey(jobId);
    }

    @Override
    public Set<ConsumeResult> getDirtyResultsInternal() throws IOException {
        return dirtyJobResults.values().stream()
                .map(ConsumeResultEntry::getJobResult)
                .collect(Collectors.toSet());
    }
}
